package com.lw.ucenter.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lw.commonutil.result.Result;
import com.lw.commonutil.result.ResultCodeEnum;
import com.lw.commonutil.utils.JwtUtils;
import com.lw.servicebase.exception.GuliException;
import com.lw.ucenter.entity.UcenterMember;
import com.lw.ucenter.service.UcenterMemberService;
import com.lw.ucenter.utils.ConstantWxPropertiesUtils;
import com.lw.ucenter.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
public class WxController {
    @Autowired
    private UcenterMemberService ucenterMemberService;

    //返回微信二维码
    @GetMapping("/getLogin")
    public String genLogin()   {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new GuliException( ResultCodeEnum.FAIL);
        }
        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "lw");
        return "redirect:"+qrcodeUrl;
    }
    //微信回调地址
    @GetMapping("/callback")
    public String callback(String code){
        try {
            //第一步，获取临时票据 code
            //第二步，拿着code，请求微信固定地址，得到两个值
            StringBuffer baseAccessTokenUrl = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                    .append("?appid=%s")
                    .append("&secret=%s")
                    .append("&code=%s")
                    .append("&grant_type=authorization_code");
            String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                    ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                    ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                    code);
            String accessTokenInfo= HttpClientUtils.get( accessTokenUrl );
            JSONObject parseObject = JSONObject.parseObject( accessTokenInfo );
            //得到微信id 和access_token
            String access_token = parseObject.getString( "access_token" );
            String openid = parseObject.getString( "openid" );
            //通过openid查询数据库是否有当前微信信息
            QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
            wrapper.eq( "openid",openid );
            UcenterMember member = ucenterMemberService.getOne( wrapper );
            if (member==null){
                //向数据库添加信息
                //通过openid和access_token得到微信用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get( userInfoUrl );
                JSONObject userInfo = JSONObject.parseObject( resultInfo );
                System.out.println(userInfo);
                //将用户信息保存到数据库
                member=new UcenterMember();
                member.setNickname( userInfo.getString( "nickname" ) );
                member.setAvatar( userInfo.getString( "headimgurl" ) );
                member.setOpenid( openid );
                member.setIsDisabled( 0 );
                ucenterMemberService.save( member );
            }
            //返回token
            String jwtToken = JwtUtils.getJwtToken( member.getId(), member.getNickname() );
            return "redirect:"+ConstantWxPropertiesUtils.GULI_BASE_URL+"?token="+jwtToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException( ResultCodeEnum.FAIL );
        }
    }

}
